package com.rest.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.api.model.ApiService;
import com.api.rest.RestHandler;
import com.api.rest.model.RestClass;
import com.api.service.ServiceHandler;
import com.util.LoadPackage;
import com.util.PathLocator;

public class ApiRestHandler {

	private final Map<Class<?>, RestClass> classes = new HashMap<Class<?>, RestClass>();;
	private final Map<Class<?>, ApiService> services = new HashMap<Class<?>, ApiService>();;

	private List<Class<?>> apiClasses;
	private String apiVersion;

	private final RestHandler restHandler;
	private final ServiceHandler serviceHandler;

	private final String jarPath;

	public ApiRestHandler(String jarPath, RestHandler restHandler, ServiceHandler serviceHandler) {
		if (restHandler == null || serviceHandler == null) {
			throw new IllegalArgumentException("RestHandler and ServiceHandler cannot be null");
		}
		this.restHandler = restHandler;
		this.serviceHandler = serviceHandler;

		if (jarPath == null) {
			jarPath = "";
		}
		jarPath = PathLocator.getClassesPath() + jarPath;
		if (!jarPath.endsWith("/")) {
			jarPath += "/";
		}
		this.jarPath = jarPath;
	}

	public void loadApiRest(String jarName) {

		this.classes.clear();
		this.services.clear();

		this.apiVersion = generateApiVersion(jarName);

		apiClasses = LoadPackage.getInterfaces(jarPath + jarName, "com.zyncro.api");
		for (Class<?> aClass : apiClasses) {

			RestClass restClass = restHandler.getRestClass(aClass);
			this.classes.put(aClass, restClass);

			ApiService apiService = serviceHandler.getApiService(aClass);
			this.services.put(aClass, apiService);
		}
	}

	public List<Class<?>> getApis() {
		return this.apiClasses;
	}

	public RestClass getRestClass(Class<?> aClass) {
		checkApiClass(aClass);
		return this.classes.get(aClass);
	}

	public ApiService getApiService(Class<?> aClass) {
		checkApiClass(aClass);
		return this.services.get(aClass);
	}

	public String getApiVersion() {
		return this.apiVersion;
	}

	public String getJarPath() {
		return jarPath;
	}

	private void checkApiClass(Class<?> aClass) {
		if (aClass == null) {
			throw new IllegalArgumentException("Class cannot be null");
		}
		if (!this.apiClasses.contains(aClass)) {
			throw new IllegalStateException("Api class doesn't exists");
		}
	}

	private String generateApiVersion(String jarName) {
		String version = jarName.split("zyncro-api-model")[1].replace(".jar", "");
		if (version.startsWith("-")) {
			version = version.substring(1);
		}
		return version;
	}
}
